<?php
namespace API\Model;

use Think\Model;

class GoodsShoucangModel extends Model
{
  private static $obj ;
    
    public static function getInitation()
    {
        $class = __CLASS__;
        return self::$obj = !(self::$obj instanceof $class) ? new self() : self::$obj;
    }
    
    /**
     * 获取收藏信息
     */
    public function getUserInfoById($field = 'id,goods_id,pic_url,price_new,price_old,detail_title,is_type', $default = 'select')
    {
        return $this->field($field)->where('user_id = "%s"', $_SESSION['userId'])->$default();
    }
    
    protected function _before_insert(&$data, $options)
    {
        $data['create_time'] = time();
        $data['user_id']     = $_SESSION['userId'];
        $data['is_type']     = 1;
        return $data;
    }
    
    /**
     * {@inheritDoc}
     * @see \Think\Model::add()
     */
    
    public function add($data='', $options=array(), $replace=false)
    {
        if (empty($data))
        {
            return false;
        }
        $data = $this->create($data);
    
        return parent::add($data, $options, $replace);
    }
    
    /**
     * 判断该产品是否被当前登录用户收藏 
     */
    public function isCollectionByUserId($goodsId)
    {
        if (!is_numeric($goodsId))
        {
            return true;
        }
        return $this->where('user_id = "%s" and goods_id = "%s"', array($_SESSION['userId'], intval($goodsId)))->getField($this->getPk());
    }
    
    /**
     * 重新删除 
     */
    public function delete($id, $field = null)
    {
        if (empty($id) || !is_numeric($id))
        {
            return false;
        }
        $pk = $field === null ? $this->getPk() : $field;
        
        return parent::delete(array(
            'where' => array($pk => $id)
        ));
    }
}